//
//  Dictionary+Tool.swift
//  ltsp
//
//  Created by jyvyi_ios on 2022/5/7.
//

import Foundation

extension Dictionary where Key == String,Value:Any{
    
    /// 转化为可编码的字典结构
    /// - Returns: ~
    func toEncodableDictionary() -> [String:EncodableType]{
        
        return self.mapValues {
            if let value = $0 as? EncodableType{
                return value
            }
            return "\($0)"
        }
    }
    
    /// 转化为Value为String的字典
    /// - Returns: ～
    func toStringValueDictionary() -> [String:String]{
        
        return self.mapValues({"\($0)"})
    }
    
    func toData() -> Data?{
        
        guard JSONSerialization.isValidJSONObject(self) else {
            return nil
        }
        do{
            let data : Data = try JSONSerialization.data(withJSONObject: self, options: [])
            
            return data
        }
        catch{
            print("JsonSerialization Dictionary Encode Error:\(error)")
        }
        return nil
    }
}
